﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts.UI
{
    public class CustomSize : MonoBehaviour
    {
        public float AddY = 0;
        public void ContentSize()
        {
            if (gameObject.activeInHierarchy)
                StartCoroutine(DoContentSize());
        }

        public IEnumerator DoContentSize()
        {
            yield return new WaitForSeconds(0);
            float sizeY = 0;
            int count = transform.childCount;
            for (int k = 0; k < transform.childCount; k++)
            {
                GameObject go = transform.GetChild(k).gameObject;
                sizeY += go.GetComponent<RectTransform>().sizeDelta.y;
            }
            RectTransform tf = gameObject.GetComponent<RectTransform>();
            float y = AddY + sizeY;
            tf.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, y);

            var partentGroup = transform.GetComponentInParent<VerticalLayoutGroup>();
            if (partentGroup != null)

                partentGroup.SetLayoutVertical();
        }

        public void RefreshContentSize()
        {
            var contents = GetComponentsInChildren<ContentSizeFitter>();

            foreach (var child in contents)
            {
                child.SetLayoutVertical();
                child.SetLayoutHorizontal();
                RectTransform rectTrans = child.GetComponent<RectTransform>();
                LayoutRebuilder.ForceRebuildLayoutImmediate(rectTrans);
            }

            float sizeY = 0;
            for (int k = 0; k < transform.childCount; k++)
            {
                GameObject go = transform.GetChild(k).gameObject;
                if (go.activeInHierarchy)
                    sizeY += go.GetComponent<RectTransform>().sizeDelta.y;
            }

            RectTransform tf = gameObject.GetComponent<RectTransform>();
            float y = AddY + sizeY;

            tf.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, y);
        }
    }
}